﻿using System;
using System.Linq;
using System.Collections.Generic;

namespace HashFoo.Core
{
    /// <summary>
    /// Type conversion utilities
    /// </summary>
    public static class ConvertUtil
    {
        /// <summary>
        /// Converts a string of hex digits to a byte[].  String can be optionally prefixed with "0x"
        /// </summary>
        /// <param name="hex"></param>
        /// <returns></returns>
        public static byte[] StringToByteArray(string hex)
        {
            if (hex.StartsWith("0x")) hex = hex.Substring(2);

            var numberChars = hex.Length;
            var bytes = new byte[numberChars / 2];
            for (var i = 0; i < numberChars; i += 2) bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);

            return bytes;
        }
    }
}